package com.atguigu.gulimall.auto.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.auto.feign.MemberFeignService;
import com.atguigu.common.vo.MemberRespVo;
import com.atguigu.gulimall.auto.vo.SocialUser;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;

/**
 * @author kabuda
 * @create 2022-11-30 13:50
 */
@Controller
public class OAuth2Controller {

    @Autowired
    private MemberFeignService memberFeignService;

    @GetMapping("/oauth2.0/weibo/success")
    public String weibo(@RequestParam("code")String code,HttpSession session) throws Exception {
        HashMap<String, String> map = new HashMap<>();
        map.put("client_id","2249641633");
        map.put("client_secret","30268e2e690d68aed3d4db9c2ea95c00");
        map.put("grant_type","authorization_code");
        map.put("redirect_uri","http://auth.gulimall.com/oauth2.0/weibo/success");
        map.put("code",code);
        //发送请求获取token
        HttpResponse response = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token", "post", new HashMap<>(), map,new HashMap<>());

        if(response.getStatusLine().getStatusCode()==200){
            //处理请求
            String json = EntityUtils.toString(response.getEntity());
            SocialUser socialUser = JSON.parseObject(json, SocialUser.class);
            R r=memberFeignService.authlogin(socialUser);
            if(r.getCode()==0){
                MemberRespVo member = r.getData("member", new TypeReference<MemberRespVo>() {
                });
                //存储session到redis（默认是内存）
                //TODO 默认作用域是当前域，解决子域跨域问题
                //TODO 使用Json序列化方式存储session到redis,方便查看
                session.setAttribute(AuthServerConstant.LOGIN_USER,member);
                System.out.println(member.getNickname());
                return "redirect:http://gulimall.com";
            }else{
                return "redirect:http://auth.gulimall.com/login.html";
            }
        }else{
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }
}
